package job

import (
	logger2 "booksmart/book/pkg/logger"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/robfig/cron/v3"
	"time"
)

type RankingBuilder struct {
	p *prometheus.SummaryVec
	l logger2.LoggerV1
}

func NewRankingBuilder(opt prometheus.SummaryOpts, l logger2.LoggerV1) *RankingBuilder {
	p := prometheus.NewSummaryVec(opt, []string{"name"})
	prometheus.MustRegister(p)
	return &RankingBuilder{p: p, l: l}
}

func (r *RankingBuilder) build(job Job) cron.Job {
	name := job.Name()
	return cronJobFuncAdapter(func() error {
		start := time.Now()
		r.l.Info("任务开始", logger2.String("job", name))
		defer func() {
			r.l.Info("任务结束", logger2.String("job", name))
			duration := time.Since(start)
			r.p.WithLabelValues(name).Observe(duration.Seconds())
		}()
		err := job.Run()
		if err != nil {
			r.l.Error("运行任务失败", logger2.Error(err),
				logger2.String("job name", name))
		}
		return nil
	})
}

type cronJobFuncAdapter func() error

func (c cronJobFuncAdapter) Run() {
	_ = c()
}
